package cn.bevisoft.casex.web.controller;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import cn.bevisoft.casex.biz.manager.UserMananger;
import cn.bevisoft.casex.biz.manager.exception.PasswordIncorrectException;
import cn.bevisoft.casex.biz.manager.exception.UserNotFoundException;
import cn.bevisoft.casex.dal.model.User;

@Controller
@RequestMapping("/admin/login.htmlx")
public class LoginController extends BaseController {

	private static final Logger log = LoggerFactory
			.getLogger(LoginController.class);

	// 用户不存在
	private static final String ERROR_CODE_USER_NOT_FOUND = "ERROR_CODE_USER_NOT_FOUND";
	// 密码不正确
	private static final String ERROR_CODE_PASSWORD_INCORRECT = "ERROR_CODE_PASSWORD_INCORRECT";

	@Autowired
	@Resource(name = "userMananger")
	private UserMananger userMananger;

	@RequestMapping(params = "method=prelogin")
	public ModelAndView preLogin(HttpServletRequest request, HttpSession session) {
		log.info("preLogin:session.id:" + request.getSession().getId());

		String validateNumber = buildValidateNumber();

		session.setAttribute("validateNumber", validateNumber);

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("validateNumber", validateNumber);

		return new ModelAndView("login", resultMap);
	}

	/**
	 * 提交登录相关信息，作登录处理。
	 * 
	 * @param loginId
	 *            登录帐号
	 * @param password
	 *            密码
	 * @param validateNumber
	 *            验证码
	 * @return
	 */
	@RequestMapping(value = "/login.htmlx", params = "method=login", method = RequestMethod.POST)
	public ModelAndView login(HttpSession session,
			@RequestParam("loginId") String loginId,
			@RequestParam("password") String password,
			@RequestParam("validateNumber") String validateNumber) {
		log.info("loginId=" + loginId + ",password=" + password
				+ ",validateNumber=" + validateNumber);
		String loginErrorCode = null;

		// 验证表单（验证用户名和密码的基本检 查，验证码是否正确，如果出错，要重新生成验证码）

		// 验证用户和密码是否正确

		User user = null;
		try {
			user = this.userMananger.login(loginId, password);
		} catch (UserNotFoundException e) {
			loginErrorCode = ERROR_CODE_USER_NOT_FOUND;
			log.warn("user login failed,because of user not found.", e);
		} catch (PasswordIncorrectException e) {
			loginErrorCode = ERROR_CODE_PASSWORD_INCORRECT;
			log.warn("user login failed,becase of password incorrect.", e);
		}

		Map<String, Object> responseMap = new HashMap<String, Object>();
		if (user != null) {
			log.info("user login success:loginId=" + loginId);
			responseMap.put("user", user);
			session.setAttribute(SESSION_USER, user);
			return new ModelAndView("login");

		} else {
			responseMap.put(ERROR_CODE, loginErrorCode);

			String validateNumber2 = this.buildValidateNumber();

			responseMap.put("validateNumber", validateNumber2);
			responseMap.put("loginId", loginId);
			session.setAttribute("validateNumber", validateNumber2);

			return new ModelAndView("login", responseMap);
		}
	}

	/**
	 * 生成6位数字验证（用随机数生成）
	 * 
	 * @return
	 */
	private String buildValidateNumber() {
		DecimalFormat decimalFormat = new DecimalFormat("000000");
		return decimalFormat.format(Math.random() * 1000000);
	}

	@RequestMapping
	public ModelAndView other(HttpServletRequest request, HttpSession session) {
		log.info("other:session.id:" + request.getSession().getId());

		return new ModelAndView("login");
	}

}
